package com.aqielife.demo.elasticsearch.service.impl;

import com.aqielife.demo.elasticsearch.dao.StudentRepository;
import com.aqielife.demo.elasticsearch.entity.StudentEs;
import com.aqielife.demo.elasticsearch.service.IStudentSearchService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author aqie
 * @date 2022/02/07 14:43
 * @desc
 */
@Slf4j
@AllArgsConstructor
@Service
public class StudentSearchServiceImpl implements IStudentSearchService {

  private final StudentRepository studentRepository;

  private final ElasticsearchRestTemplate elasticsearchRestTemplate;


  @Override
  public void deleteAll() {
    studentRepository.deleteAll();
  }

  @Override
  public void saveAll(List<StudentEs> list) {
    studentRepository.saveAll(list);
  }

  @Override
  public StudentEs createOrUpdate(StudentEs studentEs) {
    return studentRepository.save(studentEs);
  }

  @Override
  public PageImpl<StudentEs> searchStudent(String name, Integer current, Integer size) {
    // 这里比常规减一
    Pageable pageable = PageRequest.of(current - 1, size);

    BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
    MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", name);
    boolBuilder.must(matchQuery);


    NativeSearchQuery nativeSearchQueryBuilder = new NativeSearchQuery(boolBuilder);
    nativeSearchQueryBuilder.setPageable(pageable);
    String dsl = Objects.requireNonNull(nativeSearchQueryBuilder.getQuery()).toString();
    log.info("DSL {}", dsl);
    SearchHits<StudentEs> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder, StudentEs.class);
    if(searchHits.getTotalHits()<=0){
      return new PageImpl<>(Collections.emptyList(),pageable,0);
    }
    List<StudentEs> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
    return new PageImpl<>(searchProductList,pageable,searchHits.getTotalHits());
  }
}
